package com.clkj.zhonghui.service.user;

import com.alibaba.fastjson.JSONObject;
import com.clkj.zhonghui.dao.stored.VersionMapper;
import com.clkj.zhonghui.dao.user.UserAddrMapper;
import com.clkj.zhonghui.dao.user.UserMapper;
import com.clkj.zhonghui.pojo.common.*;
import com.clkj.zhonghui.pojo.points.RebateRelations;
import com.clkj.zhonghui.pojo.stored.Version;
import com.clkj.zhonghui.pojo.user.User;
import com.clkj.zhonghui.pojo.user.UserAddr;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author yawang
 * @create 2024/07/19 09:38:42
 **/
@Service
public class UserServiceImpl implements UserService{
    @Autowired
    private UserAddrMapper userAddrMapper;
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private VersionMapper versionMapper;

    private Map map;

    @Override
    public List<UserAddr> listUserAddress(Integer userId) {
        Example example  = new Example(UserAddr.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userId",userId);
        example.orderBy("addressId").desc();
        return userAddrMapper.selectByExample(example);
    }

    @Override
    public void addUserAddress(UserAddr userAddr,Integer flag) {
        if(flag.equals(0)){
            userAddrMapper.insertSelective(userAddr);
        }else {
            userAddrMapper.updateByPrimaryKeySelective(userAddr);
        }


    }

    @Override
    public void deleteUserAddress(Integer addressId) {
        userAddrMapper.deleteByPrimaryKey(addressId);

    }

    @Override
    public Map login(String unionId, String openId, String userName, String userImg, String userSex) {
        Example example  = new Example(User.class);
        Example.Criteria criteria =example.createCriteria();
        criteria.andEqualTo("unionId",unionId);
        User user = userMapper.selectOneByExample(example);
        if(user==null){
            user = new User();
            user.setShareId(0);
            user.setIfDown(0);
            user.setUserImg(userImg);
            user.setUserName(userName);
            user.setOpenId(openId);
            user.setShopId(0);
            user.setUnionId(unionId);
            userMapper.addUser(user);
        }
        map = new HashMap();
        map.put("user",user.getUserId());
        return map;
    }

    @Override
    public User EditUser(User user, HttpServletRequest request) {
        MultipartFile file = ((MultipartRequest) request).getFile("file");
        String fileName = "";
        if (file != null) {
            fileName  = OSSUtil.uploadingImg(file,"zhonghui/user");
            user.setUserImg(fileName);
        }
        userMapper.updateByPrimaryKeySelective(user);
        return userMapper.selectByPrimaryKey(user.getUserId());
    }

    @Override
    public List<Version> listNewVer() {
        return versionMapper.listNewVer();
    }

    @Override
    public List<Version> listVer() {
        return versionMapper.listVer();
    }

    @Override
    public void addVer(Version version) {
        versionMapper.insertSelective(version);
    }


    @Override
    public Map loginMini(String code,Integer parentId) throws ParseException {
        System.out.println(code);
        Map<String, String> results = new HashMap<>(); // 存放所有返回消息（Token及其有效时长、openid）

        Map<String, String> params = new HashMap<>(); // 创建一个存放参数的Map
        params.put("APPID", "wxc654e2d4c9a8cf7f"); // 设置小程序id
        params.put("APPSECRET", "4826eb440a04bb382103945ae6ea8421"); // 设置小程序密码
        // 拼接请求URL
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + params.get("APPID") + "&secret=" + params.get("APPSECRET") + "&js_code=" + code + "&grant_type=authorization_code";
        JSONObject demoJson = Util.getResult(url); // 发送请求并获取响应结果
        System.out.println(demoJson);
        String openId = demoJson.getString("openid"); // 从响应结果中获取openid
        String unionid = demoJson.getString("unionid"); // 从响应结果中获取unionid
        Map<String, Object> users = userMapper.getUserByopenId(openId); // 根据unionid查询用户信息
        Integer user_id = 0;
        Map res = new HashMap<>();
        if (users == null && openId != "") { // 如果用户不存在且openid不为空
            User user = new User(); // 创建一个新的用户对象88
            user.setOpenId(openId);
            if(parentId!=0){
                user.setReferrerId(parentId);
            }else {
                user.setReferrerId(0);
            }
            user.setUnionId(unionid);
            //user.setShopId(Integer.parseInt(shopId)); // 设置用户的社区ID为传入的shopId

            user.setRegisterTime(DateFormatHelper.currentTimes());
            userMapper.addUser(user);
            // 设置用户的注册时间为当前时间
            user_id =  user.getUserId(); // 将新用户添加到数据库，并获取用户ID
        } else {
            user_id = Integer.parseInt(users.get("user_id").toString()); // 如果用户已存在，则直接获取用户ID
        }
        // 查询用户信息
        User user = userMapper.getUserId(user_id); // 根据用户ID查询用户信息
        res.put("user_id", user_id); // 将用户ID放入结果Map中
        res.put("user", user); // 将用户对象放入结果Map中
        res.put("openId", openId); // 将openid放入结果Map中
        System.out.println(user_id + "什么时候到这里");
        return res;
    }

    @Override
    public List<User> selectUser(Integer flag, String name, Integer id) {
        List<User> user = new ArrayList<>();
        Example example = new Example(User.class);
        if (flag != -1) {
            if (flag == 0) {
                example = new Example(User.class);
                Example.Criteria criteria = example.createCriteria();
                criteria.andEqualTo("userId", id);
            } else if (flag == 1) {
                example = new Example(User.class);
                Example.Criteria criteria = example.createCriteria();
                criteria.andLike("userName", "%" + name + "%");
            }
        }
        user = userMapper.selectByExample(example);
        return user;
    }

    @Override
    public Map listLowerUser(Integer userId) {
        Map map = new HashMap();
        Example example = new Example(User.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("referrerId", userId);
        List<User> users = userMapper.selectByExample(example);
        List<Integer> userid = users.stream().map(User::getUserId).collect(Collectors.toList());
        List<User> userList=new ArrayList<>();
        if(userid.size()>1){
            example = new Example(User.class);
            criteria = example.createCriteria();
            criteria.andIn("referrerId", userid);
            userList = userMapper.selectByExample(example);
        }

        example = new Example(User.class);
        criteria = example.createCriteria();
        criteria.andEqualTo("userId", userId);
        User user = userMapper.selectOneByExample(example);
        map.put("user", user);
        map.put("xj", users);
        map.put("xxj", userList);
        return map;
    }

    @Override
    public Map listHigherUser(Integer userId) {
        Map map =new HashMap();
        User one = new User();
        User two = new User();
        Example example = new Example(User.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userId",userId);
        User user = userMapper.selectOneByExample(example);
        if (user.getReferrerId()!=null && user.getReferrerId()!=0) {
            example = new Example(User.class);
            criteria = example.createCriteria();
            criteria.andEqualTo("userId",user.getReferrerId());
            one =userMapper.selectOneByExample(example);
            map.put("pater",one);
        }else {
            map.put("pater",null);
        }
        if(one.getReferrerId()!=null && user.getReferrerId()!=0){
            example = new Example(User.class);
            criteria = example.createCriteria();
            criteria.andEqualTo("userId",one.getReferrerId());
            two = userMapper.selectOneByExample(example);
            map.put("grandsire",two);
        }else {
            map.put("grandsire",null);
        }
        return map;
    }

    @Override
    public void unbindUser(Integer userId) {
        userMapper.unbindUser(userId);
    }

    @Override
    public void editUsernameAndTf(String userTel, String name, Integer userId) {
        userMapper.editUsernameAndTf(userTel,name,userId);
    }


}
